
/*封装axios库 进阶版*/

import axios from 'axios'
import Cookies from "js-cookie";
import router from "../router";
// import domain from "../../domain";
import {Message} from "element-ui"
import store from "@/store";
import { CacheUtils } from './cacheUtils.js';
import qs from 'qs'
import Vue from "vue";
// const target = domain.target
//create an axios instance
const service = axios.create({
  baseURL: "http://localhost:3000", // api 的 base_url
  timeout: 5000 // request timeout //设置请求时长
})

service.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  // 判断是否存在token，如果存在将每个页面header都添加token
  if (Object.keys(CacheUtils.cache).length == 0){
    // 开启全局loading
  }

  var token = Cookies.get('token')
  if (token != null && token !== '') {
    config.headers.common['Authorization'] = ' Bearer ' + token
  }

  let cacheKey = config.url;
  const method = config.method.toLowerCase();
  if (method === 'get' && config.params && typeof config.params === 'object') {
    cacheKey += qs.stringify(config.params, { addQueryPrefix: true });
  }

  if (['post', 'put', 'patch'].includes(method) && config.data && typeof config.data === 'object') {
    // config.data = qs.stringify(config.data);
    cacheKey += `_${qs.stringify(config.data, { arrayFormat: 'brackets' })}`;  // 将对象转换成以&拼接的形式
  }

  // 每次发送请求之前将上一个未完成的相同请求进行中断
  CacheUtils.cache[cacheKey] && CacheUtils.clearCache(cacheKey);

  // 将当前请求所对应的取消函数存入缓存
  config.cancelToken = new axios.CancelToken(function executor(c) {
    CacheUtils.cache[cacheKey] = c;
    // store.commit('cancelToken/addCancelToken', {cacheKey,c}) // 假设语法正确
    // 在全局路由处  store.commit('cancelToken/clearCancelToken')
  });

  // 临时保存 cacheKey，用于在响应拦截器中清除缓存
  config.cacheKey = cacheKey;

  return config;

}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

service.interceptors.response.use(function(response) {
  if (Object.keys(CacheUtils.cache).length == 0){
    // 关闭 全局 loading
  }
  // 响应接收之后清除缓存
  if (!!response.config.cacheKey){
    console.log("response delete cacheKey")
    const cacheKey = response.config.cacheKey; // cancel
    delete CacheUtils.cache[cacheKey]; // cancel
    // delete store.state.cancelToken.cache[cacheKey] // 在这删
    // store.commit('cancelToken/clearCancelToken',cacheKey)  // 去vuex中删
  }

  return response
}, function(error) {
  // 出错 也清除缓存
  if (!!response.config.cacheKey){
    console.log("response delete cacheKey")
    const cacheKey = response.config.cacheKey; // cancel
    delete CacheUtils.cache[cacheKey]; // cancel
    // delete store.state.cancelToken.cache[cacheKey]
    // store.commit('cancelToken/clearCancelToken',cacheKey)  // 去vuex中删
  }

  if (error.response) {
    switch (error.response.status) {
      case 401:
        router.replace({
          path: '/login',
          query: { redirect: router.currentRoute.fullPath }
        })
        Cookies.remove('user')
        Cookies.remove('token')
        Cookies.remove('refresh_token')
        Cookies.remove('realusername')
    }
  }
  return Promise.reject(error)
})


// get请求
export const $get = function (url, config) {
  if (!url) throw Error('请核对请求链接是否正确')
  // const token = window.localStorage.storetoken
  const {params, headers, ...otherConfig} = config
  const header = Object.assign(headers || {}, {
    'Content-Type': 'application/json; charset=utf-8',
    // 'Auth-Token': token,
    // 'Common-Param': getCommonParam()
  })
  return service.get(url, {
    params,
    headers: header,
    ...otherConfig,
  }).catch((error)=>{Message.error(error)})
}
// post请求
export const $post = function (url, params, config = {}, type=1) {
  if (!url) throw Error('请核对请求链接是否正确')
  // const token = window.localStorage.storetoken
  // const {...otherConfig} = config
  let source
  if (type==1){
    source = {'Content-Type': 'application/json; charset=utf-8'} // json 数据
  }else if (type==2){
    source = {'Content-Type': 'multipart/form-data'} // formData表单
  }else{
    source = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'} // 普通表单
  }
  const header = Object.assign(  {}, source)
  return service.post(url, params, {
    headers: header,
    ...config,
  }).catch((error)=>{Message.error(error)})
}

// 网页卸载前清除缓存
// window.addEventListener('beforeunload', () => CacheUtils.clearCache(), false);

// Vue 中路由跳转前清除缓存
// router.beforeEach((to, from, next) => { CacheUtils.clearCache(); next(); });

// main.js 导入
// Vue.$get = Vue.prototype.$get = $get
// Vue.$post = Vue.prototype.$post = $post


